package kd.bos.kdec.pincar;

import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.ext.form.control.CustomControl;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.container.Tab;
import kd.bos.form.control.Control;
import kd.bos.form.control.Label;
import kd.bos.form.control.events.TabSelectEvent;
import kd.bos.form.control.events.TabSelectListener;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.CustomEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * i拼车首页
 * 
 * @author zhangyizhe
 *
 */
public class PinCarForMob extends AbstractFormPlugin implements TabSelectListener {

	private String[] buttons = new String[] { "startplace", "endplace", "oneclickpincar", "dingbill", "myclick",
			"quanclick", "goforworkpc", "endforworkpc" };

	@Override
	public void registerListener(EventObject e) {
		super.registerListener(e);
		this.addClickListeners(this.buttons);
		Tab tab = this.getView().getControl("tabap");// tab切换页
		tab.addTabSelectListener(this);// 监听选择tab
	}

	@Override
	public void click(EventObject evt) {
		super.click(evt);
		Control control = (Control) evt.getSource();
		String key = control.getKey();
		IFormView view = this.getView();
		IDataModel model = this.getModel();
		long userId = Long.parseLong(RequestContext.get().getUserId());// 用户Id
		long orgId = RequestContext.get().getOrgId();// 组织Id
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.equals("startplace", key)) {// 出发地址搜索
			params.put("formId", "kdec_searchplace");
			params.put("closeActionId", "startplace");
			this.showForm(params, null);// 跳转搜索页面
		} else if (StringUtils.equals("endplace", key)) {// 目的地址搜索
			params.put("formId", "kdec_searchplace");
			params.put("closeActionId", "endplace");
			this.showForm(params, null);// 跳转搜索页面
		} else if (StringUtils.equals("oneclickpincar", key)) {// 一键拼车按钮
			if (StringUtils.equals("", model.getValue("startplacetext").toString())) {
				this.getView().showMessage("请填写出发地");
				return;
			} else if (StringUtils.equals("", model.getValue("endplacetext").toString())) {
				this.getView().showMessage("请填写目的地");
				return;
			}
			this.removeDom();// 清除地图dom
			params.put("formId", "kdec_pincarbillmob");
			Map<String, Object> data = new HashMap<>();
			data.put("startplacetext", model.getValue("startplacetext"));// 出发地
			data.put("endplacetext", model.getValue("endplacetext"));// 目的地
			data.put("traveltime", model.getValue("traveltime"));// 路程时间
			data.put("distance", model.getValue("distance"));// 驾车路程距离
			data.put("taxicost", model.getValue("taxicost"));// 出租车价格
			data.put("taxicostf", model.getValue("taxicostf"));// 原始出租车价格
			data.put("startpos", model.getValue("startpos"));// 初始地坐标
			data.put("endpos", model.getValue("endpos"));// 目的地坐标
			this.showForm(params, data);// 跳转搜索页面
		} else if (StringUtils.equals("dingbill", key)) {// 行程单列表
			this.removeDom();// 清除地图dom
			params.put("formId", "kdec_pincarbilllist");
			this.showForm(params, null);// 跳转搜索页面
		} else if (StringUtils.equals("myclick", key)) {// 我的 跳转
			this.removeDom();// 清除地图dom
			params.put("formId", "kdec_pincar_my");
			this.showForm(params, null);// 跳转搜索页面
		} else if (StringUtils.equals("quanclick", key)) {// 圈子跳转
			this.removeDom();// 清除地图dom
			params.put("formId", "kdec_pincar_circle");
			this.showForm(params, null);// 跳转搜索页面
		} else if (StringUtils.equals("goforworkpc", key)) {// 上班拼车
			QFilter reportfilter = new QFilter("creator", QCP.equals, userId);
			reportfilter.and(new QFilter("orgfield", QCP.equals, orgId));
			DynamicObject report = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincar_reportbill",
					"home,homelocal,company,companylocal", reportfilter.toArray());
			if (null != report) {
				if (!StringUtils.equals("", report.getString("company"))) {//有公司信息自动绘制路线去公司
					CustomControl customcontrolap = (CustomControl) this.getControl("customcontrolap");
					Label label = this.getControl("endplace");
					label.setText(report.getString("company"));
					model.setValue("endplacetext", report.getString("company"));
					Map<String, Object> map = new HashMap<>();
					JSONObject local = JSONObject.fromObject(report.get("companylocal"));
					map.put("action", "endLocal");
					map.put("endLng", local.get("lng"));
					map.put("endLat", local.get("lat"));
					String endPos = "[" + local.get("lng") + ',' + local.get("lat") + "]";
					model.setValue("endpos", endPos);
					customcontrolap.setData(map);
				} else {
					view.showMessage("请先通过地址搜索维护公司信息");
				}
			} else {
				view.showMessage("请先通过地址搜索维护公司信息");
			}
		} else if (StringUtils.equals("endforworkpc", key)) {// 下班拼车
			QFilter reportfilter = new QFilter("creator", QCP.equals, userId);
			reportfilter.and(new QFilter("orgfield", QCP.equals, orgId));
			DynamicObject report = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincar_reportbill",
					"home,homelocal,company,companylocal", reportfilter.toArray());
			if (null != report) {
				if (!StringUtils.equals("", report.getString("home"))) {//有家信息自动绘制路线回家
					CustomControl customcontrolap = (CustomControl) this.getControl("customcontrolap");
					Label label = this.getControl("endplace");
					label.setText(report.getString("home"));
					model.setValue("endplacetext", report.getString("home"));
					Map<String, Object> map = new HashMap<>();
					JSONObject local = JSONObject.fromObject(report.get("homelocal"));
					map.put("action", "endLocal");
					map.put("endLng", local.get("lng"));
					map.put("endLat", local.get("lat"));
					String endPos = "[" + local.get("lng") + ',' + local.get("lat") + "]";
					model.setValue("endpos", endPos);
					customcontrolap.setData(map);
				} else {
					view.showMessage("请先通过地址搜索维护家信息");
				}
			} else {
				view.showMessage("请先通过地址搜索维家信息");
			}
		}
	}

	/**
	 * 页面跳转通用方法

	 */
	private void showForm(Map<String, Object> params, Map<String, Object> customParams) {
		Map<String, Object> formId = new HashMap<>();
		formId.put("formId", params.get("formId"));
		FormShowParameter showParameter = FormShowParameter.createFormShowParameter(formId);
		showParameter.getOpenStyle().setShowType(ShowType.Modal);
		if (null != params.get("closeActionId")) {
			CloseCallBack closeCallBack = new CloseCallBack(this, params.get("closeActionId").toString());
			showParameter.setCloseCallBack(closeCallBack);
		}
		if (null != customParams) {
			showParameter.setCustomParams(customParams);
		}
		this.getView().showForm(showParameter);
	}

	/**
	 * 清除地图dom元素 ps:离开页面清除dom防止不清空页面，下次进入不加载自定义控件
	 */
	private void removeDom() {
		CustomControl mapCon = (CustomControl) this.getControl("customcontrolap");
		Map<String, Object> map = new HashMap<>();
		map.put("listReturn", 1);
		mapCon.setData(map);// 清空地图dom
	}

	@Override
	public void customEvent(CustomEventArgs e) {
		super.customEvent(e);
		//自定义控件invoke触发
		IDataModel model = this.getModel();
		String eventName = e.getEventName();
		String setStart = "";
		String startLngLat = "";
		//根据标识触发不同方法
		if (StringUtils.equals("result", eventName)) {// 前端返回初始地坐标与建筑
			Label label = this.getControl("startplace");
			String eventArgs = e.getEventArgs();
			JSONObject jsonObject = JSONObject.fromObject(eventArgs);
			 setStart = jsonObject.getString("setStart");
			 startLngLat = jsonObject.get("startLngLat").toString();
			label.setText(setStart);//赋值初始地名
			model.setValue("startplacetext", setStart);
			model.setValue("startpos", startLngLat);

		} else if (StringUtils.equals("drivingDraw", eventName)) {//路线绘制完成返回的信息
			String taxiCost = "";
			String time = "";
			String distance = "";
			JSONObject jsonObject = JSONObject.fromObject(e.getEventArgs());
			this.getView().setEnable(true,"oneclickpincar");
			if (jsonObject.containsKey("issuccess")){
				String issuccess=jsonObject.getString("issuccess");
				if (issuccess.equals("false")){
					this.getView().showTipNotification("路线绘制失败，请重新选择起始或终点地址",3000);
					this.getView().setEnable(false,"oneclickpincar");
					return;
				}
			}
				if (jsonObject.containsKey("taxi_cost")) {
					int cost = (Integer) jsonObject.get("taxi_cost");
					model.setValue("taxicostf", cost);//出租车价钱原始
					int costpin = cost / 2;// 对拼车给出建议价
					int costpin4 = cost / 5;
					taxiCost = String.valueOf(costpin) + "元(拼成价格约" + String.valueOf(costpin4) + "元)";
				}
				if (jsonObject.containsKey("time")) {
					time = jsonObject.get("taxi_cost").toString();
				}
				if (jsonObject.containsKey("distance")) {
					distance = jsonObject.get("distance").toString();
				}
			model.setValue("taxicost", taxiCost);//计算完成的推荐价格string
			model.setValue("traveltime", time);//全程时长
			model.setValue("distance", distance);//距离
		}
	}

	@Override
	public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
		//搜索也关闭返回的数据处理
		super.closedCallBack(closedCallBackEvent);
		IDataModel model = this.getModel();
		String actionId = closedCallBackEvent.getActionId();
		Map<String, Object> re = (Map<String, Object>) closedCallBackEvent.getReturnData();//搜索返回的数据
		CustomControl control = (CustomControl) this.getControl("customcontrolap");
		String place = re.get("place").toString();
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.equals("startplace", actionId) && !StringUtils.equals("", place)) {//前端的地图始发地
			Label label = this.getControl("startplace");
			label.setText(place);
			model.setValue("startplacetext", place);//赋值初始地标签
			JSONObject local = JSONObject.fromObject(re.get("local"));
			map.put("action", "startLocal");//标识
			map.put("startLng", local.get("lng"));
			map.put("startLat", local.get("lat"));
			String startPos = "[" + local.get("lng") + ',' + local.get("lat") + "]";
			model.setValue("startpos", startPos);//坐标
			control.setData(map);
		} else if (StringUtils.equals("endplace", actionId) && !StringUtils.equals("", place)) {//前端的地图目的地
			Label label = this.getControl("endplace");
			label.setText(place);
			model.setValue("endplacetext", place);//赋值目的地标签
			JSONObject local = JSONObject.fromObject(re.get("local"));
			map.put("action", "endLocal");//标识
			map.put("endLng", local.get("lng"));
			map.put("endLat", local.get("lat"));
			String endPos = "[" + local.get("lng") + ',' + local.get("lat") + "]";
			model.setValue("endpos", endPos);//坐标
			control.setData(map);
		}
	}

	@Override
	public void tabSelected(TabSelectEvent arg0) {
		String tabKey = arg0.getTabKey();
		if (StringUtils.equals(tabKey, "tabdriver")) {// 切换页签
			this.removeDom();// 清除地图dom
			Map<String, Object> formId = new HashMap<>();
			formId.put("formId", "kdec_pincar_driver");
			this.showForm(formId, null);// 跳转搜索页面

		}
	}
}
